<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <!-- <el-form-item label="服务器" prop="serverId">
        <el-input
          v-model="queryParams.serverId"
          placeholder="请输入服务器ID"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item> -->

      <el-form-item label="服务器" prop="serverId">
        <el-select v-model="queryParams.serverId">
          <el-option
            v-for="item in serverOptions"
            :key="item.serverId"
            :label="item.serverName"
            :value="item.serverId"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
          <el-option
            v-for="dict in dict.type.sys_normal_disable"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['lbconfig:servercrt:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['lbconfig:servercrt:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['lbconfig:servercrt:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['lbconfig:servercrt:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="servercrtList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="标识ID" align="center" prop="id" />
      <!-- <el-table-column label="服务器ID" align="center" prop="serverId" /> -->
      
      <el-table-column label="服务器" align="center" prop="serverId" >
        <template slot-scope="scope">
          <span>{{ serverMap.get(Number(scope.row.serverId))}}</span>
        </template>
      </el-table-column>
      <el-table-column label="端口" align="center" prop="crtPort" />
      <el-table-column label="证书名称" align="center" prop="crtName" />
      <el-table-column label="状态" align="center" prop="status">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.object_status" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-download"
            @click="handleDownload(scope.row)"
            v-hasPermi="['lbconfig:servercrt:edit']"
          >下载</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['lbconfig:servercrt:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['lbconfig:servercrt:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改服务器证书对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="服务器" prop="serverId">
          
          <el-select v-model="form.serverId" :disabled="true">
            <el-option
              v-for="item in serverOptions"
              :key="item.serverId"
              :label="item.serverName"
              :value="item.serverId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="端口" prop="crtPort">
          <el-input-number v-model="form.crtPort" controls-position="right" :min="1" :max="65535"/>
        </el-form-item>
        <el-form-item label="证书名称" prop="crtName">
          <el-input v-model="form.crtName" :disabled="true" placeholder="请选取证书文件并上传" />
        </el-form-item>
        <el-form-item label="证书文件" prop="crtUploadPath">
          <!-- <el-input v-model="form.crtUploadPath" placeholder="请输入证书路径" /> -->
          <!-- <file-upload v-model="form.crtUploadPath"/> -->

          <el-upload
            ref="upload"
            :limit="1"
            accept=".crt"
            :file-list="upload.crtFileList"
            :headers="upload.headers"
            :action="upload.url + '?updateSupport=' + upload.updateSupport"
            :on-change="handleFileChange"
            :on-remove="handleFileRemove"
            :disabled="upload.isUploading"
            :on-progress="handleFileUploadProgress"
            :on-success="handleFileSuccess"
            :auto-upload="false"
          >
            <el-button slot="trigger" size="small" type="primary">选取文件</el-button>
            <el-button style="margin-left: 10px;" size="small" type="success" @click="submitFileForm">上传服务器</el-button>
            <div class="el-upload__tip text-left" slot="tip">
              <span>仅允许导入1个crt格式证书文件。</span>
              <!-- <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;" @click="importTemplate">下载模板</el-link> -->
            </div>
          </el-upload>

        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio
              v-for="dict in dict.type.object_status"
              :key="dict.value"
              :label="dict.value"
            >{{dict.label}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listServercrt, getServercrt, delServercrt, addServercrt, updateServercrt } from "@/api/lbconfig/servercrt";
import { listBackserver } from "@/api/lbconfig/backserver";
import { getToken } from "@/utils/auth";

export default {
  name: "Servercrt",
  dicts: ['object_status'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 服务器证书表格数据
      servercrtList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      
      // 服务器ID:Name Map
      serverMap: new Map(),
      // 服务器
      serverOptions: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        serverId: null,
        status: null,
      },
      // 表单参数
      form: {
        serverId: 0,
        crtPort: 80,
        status: "1"
      },
      // 表单校验
      rules: {
        crtName: [
          { required: true, message: "请选取证书文件并上传", trigger: "blur" }
        ],
        crtPort: [
          { required: true, message: "端口不能为空", trigger: "blur" },
          // { type: 'number', min: 1, max: 65535, message: '整数，端口范围[1,65535]', trigger: 'blur' }
        ],
        serverId: [
          { required: true, message: "服务器不能为空", trigger: "blur" }
        ],
        status: [
          { required: true, message: "状态不能为空", trigger: "change" }
        ],
      },
      // 上传证书参数
      upload: {
        // 是否显示弹出层（上传证书）
        open: false,
        // 弹出层标题（上传证书）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的证书数据
        updateSupport: 0,
        crtFileList: [],
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/lbconfig/servercrt/uploadCrt"
      },
    };
  },
  created() {
    const serverId = this.$route.params && this.$route.params.serverId;
    // console.log("serverId : " + serverId);
    this.queryParams.serverId = Number(serverId);
    this.form.serverId = Number(serverId);
    this.getServerOptions();
    this.getList();
  },
  methods: {
    /** 查询服务器证书列表 */
    getList() {
      this.loading = true;
      listServercrt(this.queryParams).then(response => {
        this.servercrtList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 查询服务器列表 */
    getServerOptions() {
      listBackserver({pageNum:1,pageSize:100}).then(response => {
        // console.log(response);
        response.rows.forEach(element => {
          let option = {serverId: Number(element.id), serverName:element.serverName};
          this.serverOptions.push(option);
          this.serverMap.set(Number(element.id),element.serverName);
        });
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        crtName: "",
        crtPort: 80,
        crtUploadPath: null,
        serverId: this.queryParams.serverId,
        status: "1",
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加服务器证书";
        
      // this.$refs.upload.clearFiles();
      this.upload.crtFileList = [];
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
        
      // this.$refs.upload.clearFiles();
      this.upload.crtFileList = [];
      getServercrt(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改服务器证书";
      });
    },
    /** 下载证书操作 */
    handleDownload(row){
      const id = row.id || this.ids
      // console.log(id);
      let fileName = row.crtName;
      // console.log(fileName);
      this.download('lbconfig/servercrt/downloadCrt/'+row.id, {}, fileName)
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            console.log(this.form);
            updateServercrt(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            console.log(this.form);
            addServercrt(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除服务器证书编号为"' + ids + '"的数据项？').then(function() {
        return delServercrt(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('lbconfig/servercrt/export', {
        ...this.queryParams
      }, `servercrt_${new Date().getTime()}.xlsx`)
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      // console.log(response);
      // console.log(file);
      this.upload.open = false;
      this.upload.isUploading = false;
      // this.$refs.upload.clearFiles();
      this.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "</div>", "上传结果", { dangerouslyUseHTMLString: true });
      // this.getList();
      if(response.code == 200){
        this.form.crtName = file.name;
        this.form.crtUploadPath = response.crtUrl;
      }
    },
    handleFileChange(file){
      // this.form.crtName = file.name;
      console.log(file);
    },
    handleFileRemove(file, fileList){
      this.form.crtName = "";
    },
    // 提交上传文件
    submitFileForm() {
      // console.log(this.upload.crtFileList);
      this.$refs.upload.submit();
    }
  }
};
</script>
